package com.xd.comment2.service;

import com.xd.comment2.dao.CommentRepository;
import com.xd.comment2.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@org.springframework.stereotype.Service
public class ServiceImp implements Service {
    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public List<Comment> FindAll() {
        List<Comment> all = commentRepository.findAll();
        return all;
    }

    @Override
    public Comment findById(String id) {
        Comment comment = commentRepository.findById(id).get();
        return comment;
    }

    @Override
    public Comment saveComment(Comment comment) {
        Comment save = commentRepository.save(comment);
        return save;
    }

    @Override
    public void updateComment(String id,String idcode,String content,String name) {
        Query query=Query.query(Criteria.where(id).is(idcode));
        Update update=new Update();
        update.set(content,name);
        mongoTemplate.updateFirst(query,update,"comment");
    }

    @Override
    public void deleteCommentById(String id) {
        commentRepository.deleteById(id);
    }

    @Override
    public List<Comment> page(String parentid,int page,int size) {
        Page<Comment> comments=commentRepository.findByParentid(parentid,PageRequest.of(page-1,size));
        return comments.getContent();
    }

    @Override
    public Map<String, Object> fun7(){
        Map<String,Object> map=new HashMap<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("parentid").is("0"));
        Query query2 = new Query();
        query2.addCriteria(Criteria.where("parentid").is("1"));
        //所有数据
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        List<Comment> comments2 = mongoTemplate.find(query2, Comment.class);
        System.out.println(comments2.size());
        for (int i = 1; i <= comments.size() ; i++) {
            Criteria c1= Criteria.where("id").is(""+i);
            Criteria c2= Criteria.where("parentid").is(""+i);
            Criteria cr = new Criteria();
            Query query1 = new Query(cr.orOperator(c1,c2));
            List<Comment> comments1 = mongoTemplate.find(query1, Comment.class);
            map.put("data"+i,comments1);
        }
        return map;
    }
}
